package com.xbongbong.admin.service.impl;

import com.xbongbong.admin.domain.entity.RaidersCorpScoreEntity;
import com.xbongbong.admin.domain.entity.RaidersProductEntity;
import com.xbongbong.admin.domain.entity.RaidersScoreExchangeEntity;
import com.xbongbong.admin.model.RaidersCorpScoreModel;
import com.xbongbong.admin.model.RaidersProductModel;
import com.xbongbong.admin.model.RaidersScoreExchangeModel;
import com.xbongbong.admin.pojo.RaidersProductInfoPojo;
import com.xbongbong.admin.pojo.dto.RaidersProductExchangeDTO;
import com.xbongbong.admin.pojo.dto.RaidersProductListDTO;
import com.xbongbong.admin.pojo.vo.RaidersProductExchangeVO;
import com.xbongbong.admin.pojo.vo.RaidersProductListVO;
import com.xbongbong.admin.service.RaidersProductService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.RaidersErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.raiders.enums.RaidersPublishEnum;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.DataPermissionEnum;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * 攻略商品
 *
 * @author 徐俊杰
 * @version v1.0
 * @date 2019/9/20 11:20
 * @since v1.0
 */
@Service("raidersProductService")
public class RaidersProductServiceImpl implements RaidersProductService {
    private static final Logger LOG = LoggerFactory.getLogger(RaidersProductServiceImpl.class);

    @Resource
    private RaidersProductModel raidersProductModel;
    @Resource
    private RaidersCorpScoreModel raidersCorpScoreModel;
    @Resource
    private RaidersScoreExchangeModel raidersScoreExchangeModel;
    @Resource
    private UserModel userModel;

    @Override
    public RaidersProductListVO list(RaidersProductListDTO raidersProductListDTO) throws XbbException {
        try {
            //剩余积分
            RaidersCorpScoreEntity raidersCorpScore = raidersCorpScoreModel.getByCorpid(raidersProductListDTO.getCorpid());
            int surplusScore = (raidersCorpScore == null) ? 0: raidersCorpScore.getSurplusScore();
            //商品列表
            Map<String, Object> productMap = new HashMap<>(6);
            productMap.put("del", DelEnum.NORMAL.getDel());
            //已上架
            productMap.put("publish", RaidersPublishEnum.PUBLISH.getCode());
            //可兑换数量不为零
            productMap.put("numNotZero", true);
            productMap.put("columns", "id,name,instruction,score,img,publish,num");
            productMap.put("orderByStr", "add_time desc");
            productMap.put("page", raidersProductListDTO.getPage());
            PageHelper pageHelper = PageHelperUtil.getPageHelper(productMap, raidersProductModel, raidersProductListDTO.getPageSize());
            List<RaidersProductEntity> productList = (List<RaidersProductEntity>) PageHelperUtil.getEntityList(productMap, pageHelper, raidersProductModel);
            //封装返回参数
            List<RaidersProductInfoPojo> productInfoList = new ArrayList<>();
            for (RaidersProductEntity product : productList) {
                RaidersProductInfoPojo productInfo = new RaidersProductInfoPojo();
                //复制商品信息
                BeanUtil.copyProperties(product, productInfo);
                productInfoList.add(productInfo);
            }
            UserVO userVO = raidersProductListDTO.getLoginUser();
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(userVO, userEntity);
            Integer dataPermission = userModel.getDataPermission(userEntity, true);
            int scoreEntryFlag = Objects.equals(dataPermission, DataPermissionEnum.ALL.getCode()) ? 1 : 0;
            return new RaidersProductListVO(scoreEntryFlag, surplusScore, pageHelper, productInfoList);
        } catch (Exception e) {
            LOG.error("攻略商品列表报错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public RaidersProductExchangeVO exchange(RaidersProductExchangeDTO raidersProductExchangeDTO) throws XbbException {
        RaidersProductExchangeVO raidersProductExchangeVO = new RaidersProductExchangeVO();
        try {
            UserVO userVO = raidersProductExchangeDTO.getLoginUser();
            UserEntity userEntity = new UserEntity();
            BeanUtil.copyProperties(userVO, userEntity);
            Integer dataPermission = userModel.getDataPermission(userEntity, true);
            if (!Objects.equals(dataPermission, DataPermissionEnum.ALL.getCode())) {
                throw new XbbException(RaidersErrorCodeEnum.API_ERROR_800033, RaidersErrorCodeEnum.API_ERROR_800033.getMsg());
            }
            //获取商品
            Long id = raidersProductExchangeDTO.getId();
            RaidersProductEntity product = raidersProductModel.getByKey(id);
            if (product == null || product.getDel() == 1) {
                throw new XbbException(RaidersErrorCodeEnum.API_ERROR_800005, RaidersErrorCodeEnum.API_ERROR_800005.getMsg(), I18nMessageUtil.getMessage(I18nStringConstant.PRODUCT));
            }
            /*******************验证商品是否合法*******************/
            Integer num = product.getNum();
            boolean flag = Objects.equals(product.getPublish(), RaidersPublishEnum.UN_PUBLISH.getCode()) || (num <= 0);
            if (flag) {
                throw new XbbException(RaidersErrorCodeEnum.API_ERROR_800018, RaidersErrorCodeEnum.API_ERROR_800018.getMsg());
            }
            String corpid = raidersProductExchangeDTO.getCorpid();
            //剩余积分
            RaidersCorpScoreEntity raidersCorpScore = raidersCorpScoreModel.getByCorpid(corpid);
            int surplusScore = (raidersCorpScore == null) ? 0 : raidersCorpScore.getSurplusScore();
            int score = product.getScore();
            surplusScore -= score;
            if (surplusScore < 0) {
                throw new XbbException(RaidersErrorCodeEnum.API_ERROR_800029, RaidersErrorCodeEnum.API_ERROR_800029.getMsg());
            }
            //更新商品信息
            num--;
            product.setNum(num);
            if (num == 0) {
                //库存数量变为0，则自动下架
                product.setPublish(RaidersPublishEnum.UN_PUBLISH.getCode());
            }
            raidersProductModel.update(product);
            /*******************更新公司积分表的数据*******************/
            if (raidersCorpScore != null) {
                raidersCorpScore.setSurplusScore(surplusScore);
                raidersCorpScoreModel.update(raidersCorpScore);
            }
            /*******************插入兑换流水*******************/
            String uuid = UUID.randomUUID().toString();
            RaidersScoreExchangeEntity exchangeEntity = new RaidersScoreExchangeEntity();
            exchangeEntity.setCorpid(corpid);
            exchangeEntity.setCreatorId(raidersProductExchangeDTO.getUserId());
            exchangeEntity.setCostScore(score);
            exchangeEntity.setSurplusScore(surplusScore);
            exchangeEntity.setRedeemCode(uuid);
            exchangeEntity.setProductId(id);
            raidersScoreExchangeModel.insert(exchangeEntity);

            raidersProductExchangeVO.setRedeemCode(uuid);
            return raidersProductExchangeVO;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("RaidersProductServiceImpl.exchange error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }
}
